<?php

namespace app\admin\controller;

use app\admin\model\Houses as HousesModel;
use app\admin\model\User;
use app\common\library\xmwechat\offiaccount\OaService;
use app\common\library\xmwechat\payment\PayService;
use app\common\model\imchat\Message;
use app\common\model\Wxinfo;
use Throwable;
use app\common\controller\Backend;

/**
 * 悬赏付款订单管理
 */
class Orders extends Backend
{
    protected array $noNeedLogin=['refund'];
    /**
     * Orders模型对象
     * @var object
     * @phpstan-var \app\admin\model\Orders
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected array $withJoinTable = ['user'];

    protected string|array $quickSearchField = ['id', 'order_no'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\Orders;
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        /**
         * 1. withJoin 不可使用 alias 方法设置表别名，别名将自动使用关联模型名称（小写下划线命名规则）
         * 2. 以下的别名设置了主表别名，同时便于拼接查询参数等
         * 3. paginate 数据集可使用链式操作 each(function($item, $key) {}) 遍历处理
         */
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->whereIn('pay_status', [1, 3])
            ->order($order)
            ->paginate($limit)->each(function ($item) {
                $item['name'] = '-';
                if (!empty($item['house_id'])) {
                    $item['hours_info'] = $item['house_type'] == 'houses' ? (new \app\admin\model\Houses())
                        ->where(['id' => $item['house_id']])->find() : (new \app\common\model\Findstore())->where(['id' => $item['house_id']])->find();
                    $item['name'] = $item['hours_info'] ? $item['hours_info']['name'] : '-';
                }
            });
        $res->visible(['user' => ['username', 'mobile', 'nickname']]);

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    public function checksubmit()
    {
        $id = $this->request->post('id');
        $check_status = $this->request->post('check_status');
        $check_msg = $this->request->post('check_msg');
        $check_img = $this->request->post('check_img');
        $row = $this->model->where(['id' => $id])->find();
        if (!$row) {
            $this->error('订单不存在');
        }
        if (!in_array($check_status, [2, 3])) {
            $this->error('审核状态错误');
        }
        if ($check_status == 2) {
            $check = '您的赏金提现成功，请前往个人中心查看。';
            $check_str='提现成功';
            if (empty($check_img)) {
                $this->error('请上传审核图片');
            }
            $row->check_img = $check_img;
        } else {
            $check='您的赏金提现被驳回，请前往个人中心查看。';
            $check_str='已驳回';
            if (empty($check_msg)) {
                $this->error('请填写驳回原因');
            }
            $row->check_msg = $check_msg;
        }
        $chcek_upinfo = [
            'check_status' => $check_status,
            'check_time' => time(),
        ];
        $row->save($chcek_upinfo);
        try {
            $to_uid = $row['to_uid'];
            $ret = Message::insertMsg(['content' => $check, 'type' => 0, 'to_uid' =>$to_uid, 'from_uid' => 10], 10);
            $unionid = (new User())->where('id', '=',$to_uid)->value('weixin_unionid');
            $openid = (new Wxinfo())->where(['unionid' => $unionid])->value('wxopenid');// 'oyMrVspaMfT-QfD0qjaU7W-_1tBU';
            if ($openid) {
                $template_id = '10dAODMpbdJIXUt0oiNt7USIs6qYg3K5cgOwdKx_o-E';
                $data = [
                    'thing1' => ['value' => $check, 'color' => '#888888'],
                    'character_string5' => ['value' => $row['order_no'], 'color' => '#888888'],
                    'const2' => ['value' =>$check_str, 'color' => '#888888'],
                    'character_string1' => ['value' => time() . rand(999999, 1000000), 'color' => '#888888'],
                ];
                /*详细内容

工单名称
{{thing1.DATA}}
订单编号
{{character_string5.DATA}}
当前工单进度
{{const2.DATA}}
管理枚举值
跳转文案
点击查看详情
管理文案*/
                // 模板跳转链接,不跳转可忽略此参数
                $url = '';
                // 跳小程序所需数据,不需跳小程序可不用传该数据，小程序appid必须已绑定关联当前公众号
                $miniprogram = [
                    'appid' => 'wx2b1b3222bf4cab2b',
                    'pagepath' => 'pages/home/index'
                ];
                (new OaService())->sendTemplateMessage($openid, $template_id, $data, $url, $miniprogram);
            }
        } catch (\ba\Exception $exception) {

        }
        $this->success('操作成功');
    }
    public function wichecksubmit()
    {
        $id = $this->request->post('id');
        $check_status = $this->request->post('check_status');
        $check_msg = $this->request->post('check_msg');
        $check_img = $this->request->post('check_img');
        $row = (new \app\admin\model\Withdraw())->where(['id' => $id])->find();
        if (!$row) {
            $this->error('订单不存在');
        }
        if (!in_array($check_status, [2, 3])) {
            $this->error('审核状态错误');
        }
        if ($check_status == 2) {
            $check = '您的赏金提现成功，请前往个人中心查看。';
            $check_str='提现成功';
            if (empty($check_img)) {
                $this->error('请上传审核图片');
            }
            $row->check_img = $check_img;
        } else {
            $check='您的赏金提现被驳回，请前往个人中心查看。';
            $check_str='已驳回';
            if (empty($check_msg)) {
                $this->error('请填写驳回原因');
            }
            $row->check_msg = $check_msg;
        }
        $chcek_upinfo = [
            'check_status' => $check_status,
            'check_time' => time(),
        ];
        $row->save($chcek_upinfo);
        try {
            $to_uid = $row['user_id'];
            $ret = Message::insertMsg(['content' => $check, 'type' => 0, 'to_uid' =>$to_uid, 'from_uid' => 10], 10);
            $uinfo=(new User())->where('id', '=',$to_uid)->find();
            $uinfo->setDec('money',$row['money']*100);
            $unionid = (new User())->where('id', '=',$to_uid)->value('weixin_unionid');
            $openid = (new Wxinfo())->where(['unionid' => $unionid])->value('wxopenid');// 'oyMrVspaMfT-QfD0qjaU7W-_1tBU';
            if ($openid) {
                $template_id = '10dAODMpbdJIXUt0oiNt7USIs6qYg3K5cgOwdKx_o-E';
                $data = [
                    'thing1' => ['value' => $check, 'color' => '#888888'],
                    'character_string5' => ['value' => $row['order_no'], 'color' => '#888888'],
                    'const2' => ['value' =>$check_str, 'color' => '#888888'],
                    'character_string1' => ['value' => time() . rand(999999, 1000000), 'color' => '#888888'],
                ];
                /*详细内容

工单名称
{{thing1.DATA}}
订单编号
{{character_string5.DATA}}
当前工单进度
{{const2.DATA}}
管理枚举值
跳转文案
点击查看详情
管理文案*/
                // 模板跳转链接,不跳转可忽略此参数
                $url = '';
                // 跳小程序所需数据,不需跳小程序可不用传该数据，小程序appid必须已绑定关联当前公众号
                $miniprogram = [
                    'appid' => 'wx2b1b3222bf4cab2b',
                    'pagepath' => 'pages/home/index'
                ];
                (new OaService())->sendTemplateMessage($openid, $template_id, $data, $url, $miniprogram);
            }
        } catch (\ba\Exception $exception) {

        }
        $this->success('操作成功');
    }
    public function refund()
    {
        $id = $this->request->post('id/d');
        $id=181;
        $order_row = $this->model->where(['id' => $id])->find();
        $refund_result = PayService::getInstance()
            ->refunds([
            'out_trade_no' => $order_row['order_no'],
            'transaction_id' => $order_row['transaction_id'],
            'reason' => '下架房源',
            'refund_price' => $order_row['order_amount'],
            'pay_price' => $order_row['order_amount'],
        ]);
        $order_row->save(['pay_status' => 2, 'update_time' => time()]);
        $type=$order_row['house_type'];
        if ($type == 'houses') {
            $result = HousesModel::where(['id' => $id, 'user_id' => $this->auth->id])->find();
            if (!$result) {
                $this->error("房源不存在");
            }
        } else {
            $result = \app\common\model\Findstore::where(['id' => $id, 'user_id' => $this->auth->id])->find();
            if (!$result) {
                $this->error("找店不存在");
            }
        }
        $result->save(['status' => 0, 'order_id' => 0, 'update_time' => time(), 'down_time' => time()]);
        $this->success();
    }
}
